/**
 * 将启用，暂时保留，请使用igrid功能
 * ccayGrid 初始化列表控件
 * 
 * @param {Json}
 *            options 可选，设置参数
 * @return {JQDom} 对象本身
 */
$.fn.ccayGrid = function(options) {
	// 若已经初始化，则不执行再次初始化	
	if(this.attr("gtgrid_init") == "true"){
		return this;
	};
	if(this.length<1)
		return this;
	var me = this;
	var noEditPermission;
	options = options || {};
	var currLanguage = Ccay.Local.getCurrLanguage() === "zh_CN" ? "cn" : "en";
	var baseOption = {
		id : this.prop("id"),
		container : this.prop("id"),
		replaceContainer : false,
		dataset : {
			fields : [], 
			data : [],
			uniqueField : ""
		},
		pageSize : options.noPage ? 2000 : options.pageSize || Ccay.UI.Config.pager.defaultSize,
		totalRowNum : 0,
		pageNum : 1,
		pagerOp : {},
		// toolbarContent:options.noPage ? "" :"nav | goto | pagesize state",
		multiSelect : true,
		height : 372,
		width : "100%",
		// showGridMenu : true ,
		enableValidUpdate:false,// 是否开启验证编辑数据
		selectRowByCheck : false,
		pageSizeList : [].concat(Ccay.UI.Config.pager.pageSizes),
		allowPersonalized:true,
		remotePaging : true,
		autoLoad : true,
		// skin : "pink",
		showIndexColumn : true,
		language : currLanguage,
		method : "GET",
		//默认grid区域查询数据时，loading
		noLoading:false,
		// add by linshijian 2012-9-19 删除按钮开关，开启为使用一个按钮，关闭为使用两个按钮
		oneDeleteBtn:true
	}
	baseOption.dataset.uniqueField = options.uniqueField;
	$.extend(baseOption, options);
	baseOption.onComplete=function() {
		options.onComplete && options.onComplete.call(this,this._autoLoad);
		Ccay.ready(me);
	}
	var hasEditPermission = true;
	if (options.editPermission) {
		hasEditPermission = Ccay.Permission.check(options.editPermission)
	}

	// 处理转换options参数
	// 动态根据column 生成fields,并且判断column.id 是否包含对象的层次结构引用，如果有，则分析，并拆开。
	$.each(baseOption.columns, function(index, column) {
				// 如果当前用户没有编辑权限，则将每一列的column设为不可修改
				!hasEditPermission && (column.editable = false);
				if (column.ccayPermission
						&& !Ccay.Permission.check(column.ccayPermission))
					column.hidden = true;
				// 自动将grid 列标题国际化
				if (column.header) {
					column.header = $i18n(column.header);
					if(column.editor)
					{
				        if(column.editor.validRule && $.inArray('R',column.editor.validRule) > -1)
				        {  	
				        	column.title = column.header;
				        	column.header += "<font color='red'>&nbsp;*</font>";
				        }
					}
				}
				// 已经锁定的列不允许解锁、已经隐藏的列不允许显示
				if (column.frozen) {
					column.hideable=false;
					column.freezeable=false;
					column.resizable=false;
				}
				if(column.hidden && column.hideable!==true){
					column.hideable=false;
				}
				// 如果配置了checkColomn,则自动将根据check选择行
				if (column.isCheckColumn) {
					column.align = "center";
					column.id="chk";
					column.hideable=false;
					baseOption.selectRowByCheck = true;
				}
				if (!Ccay.DataHelper.isEmpty(column.id)) {
					var fieldName = column.id;
					baseOption.dataset.fields.push({
								name : fieldName,
								type : column.type || "string"
							})
				}
				(typeof column.format == "object")
						&& Ccay.UI.Grid.initRenderer(column);
				(typeof column.format == "object" && typeof column.editor == "object")
						&& Ccay.UI.Grid.initEditor(column);
				if(typeof column.editor == "object"){
					column.editor.gridid=me.prop("id");
				}
						

				if (!column.renderer) {// add by zhh, 加上过滤标示
					if (column.returnValue)
						column.renderer = function(value) {
							return "<span class='ccay-selector-value'>"
									+ encode(value) + "</span>";
						};
					else if (column.returnText)
						column.renderer = function(value) {
							return "<span class='ccay-selector-text'>"
									+ encode(value) + "</span>";
						};
				}else if(column.sortByRender){
					column.getSortValue=column.renderer;
				}
			});
	// 个性化接口实现
	if (Ccay.Personalized && Ccay.Personalized.gridProcessor && baseOption.allowPersonalized) {
		Ccay.Personalized.gridProcessor(baseOption);
	}
	var gtgrid = new Sigma.Grid(baseOption);
	// 重写gtgrid的刷新方法
	gtgrid.oldRefresh = gtgrid.refresh;
	gtgrid.refresh = function(pagedResult) {
		this.dataset && this.dataset.cleanModifiedData(true);
		if (!pagedResult) {
			gtgrid.refresh(gtgrid.dataset.data);
			return;
		}
		var data = pagedResult, pager, pageinfo = gtgrid.getPageInfo();
		if (pagedResult.result && pagedResult.pageVO) {
			data = pagedResult.result;
			pager = pagedResult.pageVO;
		}
		gtgrid.oldRefresh(data);
		if (pager)
		{
			var pagerCtr = $('#' + gtgrid.pager);
			if(pagerCtr.length)
				pagerCtr.pager({pageInf : pager});
			else
				baseOption.pagerOp.pageInf = pager;
		}

		//gtgrid.freezeBodyDiv.style.height= gtgrid.bodyDiv.clientHeight + 'px';
	}

	// 初始化Grid操作
	Ccay.UI.Grid._InitOperation(gtgrid);

	_setMapper(this, gtgrid);
	//是否初始化，处理默认查询
	gtgrid.isInit = 1;
	Ccay.UI.ajax.openCacheRequest(this);
	
	gtgrid.render();
	// 解决grid 样式bug
	/* gtgrid.freezeBodyDiv.style.top="23px"; */
	if (!options.noPage) {
		var gridid = this.id(), pagerid = gridid + '_pager', pager = $
				.create('div').id(pagerid).appendTo(this);

		gtgrid.pager = pagerid;
		var pagerOp = $.extend(true, {
					pageInf : {
						pageSize : options.pageSize || Ccay.UI.Config.pager.defaultSize,
						totalRows : baseOption.totalRowNum,
						curPage : baseOption.pageNum
					},
					pageSizes : baseOption.pageSizeList,
					fnBeforeChanged:function(pager,pageInf,oldPage,oldPageSize,fnChange){
						if(gtgrid.activeEditor)
							gtgrid.hideEditor();
						if(gtgrid.getInsertedRecords().length || gtgrid.getUpdatedRecords().length || gtgrid.getDeletedRecords().length){
							Ccay.UI.confirm("ccay.common.message.confpagersave", function(result) {
										if (result)
										{
											// 保存数据不通过时，pager不改变，否则改变pager
											var ret = gtgrid.save();
											if(ret === false ||  gtgrid.getValidRecords(true) == false){
												pageInf.curPage = oldPage;
												pageInf.pageSize = oldPageSize;
												// 取整
												pageInf.totalPages = Math.ceil(pageInf.totalRows / oldPageSize);
												$("#"+gtgrid.pager).manager().changePage(pageInf);
											} else {
												fnChange(pager,pageInf);
											}
										}
										else{
											fnChange(pager,pageInf);
											gtgrid.search();
										}
									},1);
						}
						else{
							fnChange(pager,pageInf);
							//如果grid没有初始化，则改变pager分页，不查询数据库！
							if(!gtgrid.isInit || gtgrid.dataset.data.length > 0){
								gtgrid.search()
							}else{
								var dom = pager.dom  || pager;
								dom.children('.ccay-pager-text').addClass("hide").prev().removeClass("hide");
							}
						}
						return false;
					}
//					,fnPageChanged : function(pageInf) {
//						if(gtgrid.activeEditor)
//							gtgrid.hideEditor();
//						
//						if(gtgrid.getInsertedRecords().length || gtgrid.getUpdatedRecords().length){
//							Ccay.UI.confirm("ccay.common.message.confpagersave", function(result) {
//										if (result)
//											$(gtgrid.operation.save.btn).click();
//										else
//											gtgrid.search();
//									},1);
//						}
//						else
//							gtgrid.search();
//					}
			}, baseOption.pagerOp);

		pager.css('border-top-width', 0).pager(pagerOp);
	};
	this.attr("gtgrid_init","true");
	return this;
}
/**
 * ccayGrid 重新加载
 */
$.fn.ccayGridSearch = function(datas) {
	var mapper = _getMapper(this);
	if (mapper) {
		if (datas)
			mapper.refresh(datas);
		else
			mapper.search(1);
	} else
		Ccay.Core.log("({0})没有绑定Grid对象!".format(this.attr('id')));
}

/**
 * @description 得到ccayGrid 管理对象
 * @return {Object} ccayGridManager
 */
$.fn.getCcayGridManager = function() {
	var manager = _getMapper(this);
	if (manager)
		manager.getPageVO = function() {
		
			if (manager.pager){
				var pageManager = $('#' + manager.pager).manager();
				if(pageManager.getPageInf){
					return pageManager.getPageInf()
				}
			}
			var pageinfo = manager.getPageInfo();
			return {
				pageSize : pageinfo.pageSize,
				curPage : pageinfo.pageNum,
				totalRows : pageinfo.totalRowNum
			};
		};
	return manager;
}

Ccay.UI.Grid = {};
Ccay.UI.Grid.initRenderer = function(column) {
	var format = column.format;
	if (format && typeof format.type == "string" && !column.renderer) {
		column.renderer = Ccay.UI.Grid.Renderer[format.type];
	}
	if ((format.valueField || format.displayField) && !column.renderer) {
		column.renderer = function(value) {
			if (!value)
				return "";
			return (value[format.displayField || format.valueField] || "").encode();
		};
	}
}
Ccay.UI.Grid.initEditor = function(column) {
	var formatType = column.format.type;
	delete column.format.type;
	if (typeof formatType == "string") {
		var tempEditor = Ccay.UI.Grid.Editor[formatType];
		if (tempEditor)
			$.extend(column.editor, tempEditor);

		if (!Ccay.UI.Grid.Editor[formatType]) {
			column.editor.type = formatType;
		}
		$.extend(column.editor, column.format || {});
		// 特别处理
		if (formatType == "lookup") {
			column.editor.type = "jcombo";
			var lookupType = column.format.supportLang ? "LOOKUP2:" : "LOOKUP:";
			column.editor.service = column.format.service = lookupType
					+ column.format.code;
		}
	}
}

/** grid常用渲染器配置 */
Ccay.UI.Grid.Renderer = {
	select : function(value, record, columnObj, grid) {
		if (columnObj.format.options) {
			for (var attr in columnObj.format.options) {
				if (value == attr){
					var value = columnObj.format.options[attr];
					return Ccay.DataHelper.isEmpty(value)? "": value;
				}	
			}
			return columnObj.format.options["defaultValue"] || (Ccay.DataHelper.isEmpty(value)? "": value);
		}
		return value;
	},
	language : function(value) {
		return (value == "en_US")
				? $i18n("ccay.common.label.lang.english")
				: $i18n("ccay.common.label.lang.chinese");
	},
	yesno : function(value) {
		return (value == "1")
				? $i18n("ccay.common.label.yes")
				: $i18n("ccay.common.label.no");
	},
	valid : function(value) {
		return (value == "1")
				? $i18n("ccay.common.label.valid")
				: $i18n("ccay.common.label.invalid");
	},
	date : function(value) {
		if (Ccay.DataHelper.isEmpty(value))
			return "";
		value=Ccay.Format.toDate(value)
		return value.format(Ccay.Config.Format.date);
	},
	datetime : function(value) {
		if (Ccay.DataHelper.isEmpty(value))
			return "";
		value=Ccay.Format.toDate(value)
		return value.format(Ccay.Config.Format.datetime);
	},
	href : function(value, record, columnObj, grid) {
		var tempUrl = columnObj.href || columnObj.format.href;
		for (var name in record) {
			if (record[name]) {
				var pvalue = (String)(record[name]).replace(/</g, "&lt;")
				tempUrl = tempUrl.replace(new RegExp("\\$\\{(" + name + ")\\}",
								"g"), pvalue);
			}
		}
		return "<a href='#!" + tempUrl + "'>" + value.encode() + "</a>";
	},
	jcombo : function(value, record, columnObj, grid) {
		if (columnObj.format && columnObj.format.childValueField) {
			value = value[columnObj.format.childValueField];
		}
		if (!columnObj.format.options ) {
			
			return Ccay.DataHelper.isEmpty(value)? "": value;
		}
		var options = columnObj.format.options || {};
		for (var i = 0; i < options.length; i++) {
			var item = options[i];

			if (item.value == value) {
				return item.text || "";
			}
		}
		return "";
	},
	lookup : function(value, record, columnObj, grid) {
		if (columnObj.format.code) {
			return Ccay.Component.Lookup.getMap(columnObj.format.code, "",
					columnObj.format.supportLang)[value]
					|| "";
		}
	},
	personInfo : function(value, record, columnObj) {
		var field = columnObj.format.field || "___";
		var disValue = value;
		if (value != null && typeof value == "object") {
			disValue = value[field] || value.userAccount;
			disValue = disValue || "";
		}
		if (!disValue)
			return "";
		var link = "<a href='javascript:Ccay.Component.popUserInfo(\"{0}\")'>{1}</a>"
				.formatValue(disValue, disValue);
		return link;
	},
	groupInfo : function(value, record, columnObj) {
		var field = columnObj.format.field || "___";
		var disValue = value;
		if (value != null && typeof value == "object") {
			disValue = value[field] || value.name;
		}
		var link = "<a href='javascript:Ccay.Component.popGroupInfo(\"{0}\")'>{1}</a>"
				.formatValue(disValue, disValue);
		return link;
	},
	field : function(value, record, columnObj) {
		var field = columnObj.format.field || "___";
		var disValue = value;
		if (value != null && typeof value == "object") {
			disValue = value[field];
		}
		return disValue;

	},
	jldap : function(value) {
		if (value && typeof value == "object") {
			return (value.userCN || value.userAccount) || "";
		} else {
			return value || "";
		}
	}

};
/** grid常用editor配置 */
Ccay.UI.Grid.Editor = {
	language : {
		"type" : "select",
		"options" : {
			"zh_CN" : $i18n("ccay.common.label.lang.chinese"),
			"en_US" : $i18n("ccay.common.label.lang.english")
		}
	},
	lang : {
		"type" : "select",
		"options" : {
			"zh_CN" : $i18n("ccay.common.label.lang.chinese"),
			"en_US" : $i18n("ccay.common.label.lang.english")
		}
	},
	yesno : {
		"type" : "select",
		"options" : {
			"1" : $i18n("ccay.common.label.yes"),
			"0" : $i18n("ccay.common.label.no")
		}
	},
	valid : {
		"type" : "select",
		"options" : {
			"1" : $i18n("ccay.common.label.valid"),
			"0" : $i18n("ccay.common.label.invalid")
		}
	},
	date : {
		"type" : "date",
		format : "date"
	},
	datetime : {
		"type" : "date",
		format : "datetime"
	}
};
Ccay.UI.Grid.Editor.lang = Ccay.UI.Grid.Editor.language;
Ccay.UI.Grid.Editor.yesnoicon = Ccay.UI.Grid.Editor.yesnoicon;

Ccay.GridBatch = function(insertedRecords, updatedRecords, deletedRecords) {
	this.items2Create = insertedRecords;
	this.items2Update = updatedRecords;
	this.items2Delete = deletedRecords;
}

/** 初始化Grid操作 */
Ccay.UI.Grid._InitOperation = function(grid) {
	var operation = grid.operation;
	//取到删除按钮开关设置
	var oneDeleteBtn = grid.oneDeleteBtn;
	if (operation) {
		if (operation.search) {
			if (operation.search.fn) {
				grid.search = operation.search.fn;
				if (operation.search.btn)
					$(operation.search.btn).addClass('default').click(function() { operation.search.fn() });
			} else {
				grid.search = function(isreload) { search(grid,isreload); };
				
				if (operation.search.btn) {
					$(operation.search.btn).addClass('default').click(function() { search(grid, 1); });
					var panelid = operation.search.panel;
					if (panelid) {
						var panel = $(panelid);
						if (!operation.search.fnbefore && panel.hasClass('init')) {
							grid.operation.search.fnbefore = function() {
								return $(panelid).valid();
							}
						}
//						panel.keydown(function(e) {
//							if ((window.event||e).keyCode == 13){
//								var target = $.getEventTarget(e);
//								if(target.attr('type') !== "reset")
//									$(operation.search.btn).click();
//							}	
//						})
					}
				}
			}
		}

		if (operation.save) {
			if (!operation.save.fn && operation.save.url)
				operation.save.fn = save;

			if (operation.save.btn)
				$(operation.save.btn).click(function() {grid.save();});
		}

		if (operation.add && operation.add.btn)
			$(operation.add.btn).click(function() {grid.addRow();});

		//只用一个删除按钮"标记为删除" modified by linshijian 2012-9-19
		if (oneDeleteBtn && operation.del && operation.del.btn){
			$(operation.del.btn).click(function() {
						if (grid.getSelectedRecords().length < 1) {
							Ccay.UI.topBox("ccay.common.message.gridNoSelect");
							return;
						}
						if (grid.readOnly || grid.endEdit() === false) {
							return;
						}
						grid.deleteRow(null,"one");
					});
		}
		//设置两个删除按钮"标记为删除" 和"取消删除"  modified by linshijian 2012-9-19
		if(!oneDeleteBtn && operation.del && operation.del.btn && operation.del.undoBtn){
			$(operation.del.btn).click(function() {
						if (grid.getSelectedRecords().length < 1) {
							Ccay.UI.topBox("ccay.common.message.gridNoSelect");
							return;
						}
						if (grid.readOnly || grid.endEdit() === false) {
							return;
						}
						grid.deleteRow(null,"two_del");
					});
			$(operation.del.undoBtn).click(function() {
						if (grid.getSelectedRecords().length < 1) {
							Ccay.UI.topBox("ccay.common.message.gridNoSelect");
							return;
						}
						if (grid.readOnly || grid.endEdit() === false) {
							return;
						}
						grid.deleteRow(null,"two_notdel");
					});		
		}
	}

	function search(grid, isReload) {
		var isSearch = true;
		if (grid.operation.search.fnbefore && grid.operation.search.fnbefore() == false)
			isSearch = false;

		if (isSearch) {
			var pageinfo = grid.getPageInfo(),param;
			

			if(grid.isInit){
				delete grid.isInit;
				if(!isReload)
				isReload = 1;
			}
				
			if (isReload || grid.operation.search.fnload)
			{
				isReload && (pageinfo.pageNum = 1);
				param = grid.operation.search.panel ? $(grid.operation.search.panel).jsonData(): {};
				
				// 取merge 参数
				if (typeof(grid.operation.search.params) === "object") {
					param = $.extend({},grid.operation.search.params, param);
				}else if(typeof(grid.operation.search.params) === "function"){
					param = $.extend({},grid.operation.search.params(), param);
				}
				
				if (grid.remoteSort && grid.sortInfo && grid.sortInfo.length){//排序处理
					var sort = grid.sortInfo[0];
					param.sort = sort.fieldName + ' ' + sort.sortOrder;
				}
			}
			else{
				
				var jqGrid = $('#' + grid.gridId),
					request = Ccay.UI.ajax.getLastRequest(jqGrid);
					param = request ? request.param : {};
			}
			var url = grid.operation.search.url.formatURI(pageinfo.pageSize, pageinfo.pageNum);
			var countUrl = grid.operation.search.countUrl;
			if(countUrl){
				countUrl = countUrl.formatURI(pageinfo.pageSize, pageinfo.pageNum);
			}
			var jqGrid = $('#' + grid.id),
				parent = jqGrid.parent();
			if(!grid.noLoading){
				if(parent.hasClass('ccay-grid'))
					parent.loading();
				else
				    jqGrid.loading();	
			}
			
			var ajaxOp;
			var fnrefresh = function(datas) {
				grid._inSearch = false;
				grid.refresh(datas);
				if(ajaxOp && countUrl){
					Ccay.UI.ajax($.extend({},ajaxOp,{
						url : countUrl,
						success : function(data){
							data = data.pageVO ? data.pageVO :data;
							$('#' + grid.id+"_pager").manager().changePage({totalPages : data.totalPages, totalRows:data.totalRows+1});
						}
					}))
				}
			};
			
			//加载失败时，去掉loading
			var fnError = function(textStatus, errorThrown, responseText, status){
				if(parent.hasClass('ccay-grid'))
					parent.loadingClose();
				else
				    jqGrid.loadingClose();
				grid._inSearch = false;
			}

			var insertRows = grid.getInsertedRecords();
			if (insertRows.length > 0)
				insertRows.remove();
			
			//$('#' + grid.id).loading();
			
			if (grid.operation.search.fnload)
				grid.operation.search.fnload(url, param, fnrefresh, fnError);
			else {
				ajaxOp =$.extend({
					url:url,
					success:fnrefresh,
					data:param,
					loading:false,
					error:fnError
				},grid.operation.search.ajax);
				grid._inSearch = true;
				Ccay.UI.ajax(ajaxOp,'#' + grid.id);
			}
		}
	}

	function save(grid, params) {
		Sigma.activeGrid = grid;
		Ccay.doPut(grid.operation.save.url, params, function() {
					Ccay.UI.topBox("ccay.common.message.success");
					grid.dataset.cleanModifiedData(true);
					grid.search();
				});
	}
};